<template>
	<view class="container" style="padding-bottom: 70px;">
		<!-- 搜索表单 -->
		<view class="search-collapse" v-if="checkPerms('client:experimental:query')">
			<view class="search-collapse-header" @tap="toggleSearch">
				<text class="toggle-icon">{{ showSearch ? '▲' : '▼' }}</text>
				<text class="header-text">搜索条件</text>
			</view>

			<view class="search-form" v-show="showSearch">
				<view class="form-item">
					<text class="label">任务编号：</text>
					<input class="input" placeholder="请输入任务编号" v-model="formData.jobNumber" />
				</view>

				<view class="form-item">
					<text class="label">检测性质：</text>
					<input class="input" placeholder="请输入检测性质" v-model="formData.detectionNature" />
				</view>

				<view class="form-item">
					<text class="label">紧急程度：</text>
					<picker mode="selector" :range="urgencyList" v-model="formData.urgencyDegree">
						<view class="picker">{{ formData.urgencyDegree || "请选择紧急程度" }}</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">检测方式：</text>
					<picker mode="selector" :range="detectionMethods" v-model="formData.detectionMethod">
						<view class="picker">{{ formData.detectionMethod || "请选择检测方式" }}</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">检测点位：</text>
					<input class="input" placeholder="请输入检测点位" v-model="formData.monitoringPoints" />
				</view>

				<view class="form-item">
					<text class="label">发起时间：</text>
					<picker mode="date" v-model="formData.initiationTime">
						<view class="picker">{{ formData.initiationTime || "选择日期时间" }}</view>
					</picker>
				</view>

				<view class="form-button">
					<button class="primary-btn" @click="submitForm" v-if="checkPerms('client:experimental:query')">查询</button>
					<button class="reset-btn" @click="resetForm" v-if="checkPerms('client:experimental:reset')">重置</button>
				</view>
			</view>
		</view>

		<!-- 任务列表 -->
		<scroll-view class="list" scroll-y>
			<view v-for="(item,index)  in tableData" :key="item.index" class="list-item">
				<!-- 任务卡片 -->
				<view class="card">
					<view class="card-header">
						<view class="task-id">任务编号：{{ item.taskId }}</view>
						<view class="task-status"
							:class="{ 'status-complete': item.uploadPreparation === '1' && item.uploadRecords === '1' && item.uploadHandover === '1' }">
							{{ item.uploadPreparation === '1' && item.uploadRecords === '1' && item.uploadHandover === '1' ? '已完成' : '未完成' }}
						</view>
					</view>

					<!-- 任务详情 -->
					<view class="task-info">
						<text>委托单位：</text>{{ item.entrustingUnit }}
					</view>
					<view class="task-info">
						<text>受检单位：</text>{{ item.testedUnit }}
					</view>
					<view class="task-info">
						<text>报告时间：</text>{{ item.reportTime }}
					</view>

					<!-- 文件状态 -->
					<view class="file-status">
						<text class="label"> 附件状态：</text>
						<text v-if="item.uploadExperimental === '1'" class="link-text"
							@click="showFileDialog(item,'experimental')">
							查看上传附件
						</text>
						<text v-else class="pending-text"> 待上传附件 </text>
						
						
					</view>

					<!-- 操作按钮 -->
					<view class="action-buttons">
						<button type="primary" size="mini" bindtap="uploadFiles" class="action-btn info" v-if="checkPerms('client:experimental:upload')"
							@click="uploadFiles(item)">{{ item.uploadExperimental === '1' ? '补充上传' : '上传' }}</button>
						<button class="action-btn success" type="success" size="mini" bindtap="confirmSubmit" v-if="checkPerms('client:experimental:submit')"
							@click="openDialog()">提交</button>
						<button class="action-btn danger" type=" warn" size="mini" bindtap="rejectRow" v-if="checkPerms('client:experimental:reject')"
							@click="gotoReturnPage(item)">退回</button>
						<button class="action-btn success" type="mini" v-if="checkPerms('client:experimental:pending')"
							@click="toggleSuspend(index, item)">{{ item.isStop === '待挂起' ? '挂起' : '恢复' }}</button>
					<notice :visible="confirmDialogVisible" title="提交确认" 
						 :businessType="businessType" :taskId="item.taskId" 
						 :toExamineType="'5'" :submitForm="'实验分析'"
						  @update:visible="confirmDialogVisible = $event"/>
					</view>
					
				</view>
			</view>
		</scroll-view>

		<!-- 分页组件 -->
		<view class="pagination">
			<uni-pagination :page-size="formData.pageSize" :current="formData.pageNum" :total="total" show-icon
				@change="changePage" />
		</view>
	</view>
</template>


<script>
	import notice from '../common/notice/index.vue';
	import {
		wxLoginGetCode,
		queryAuthorize,
		queryPerms
	} from "@/api/system/wechat";
	import {
		list,
		update,
		getTaskFiles,
		receiveTask,
		confirmeList,
		submitTask,
		rejectTask,
		selectDeptTree,
		selectUserByDeptId,
		toExamine,
		selectCcName
	} from "@/api/mobilebusiness";
	import {
		getToken
	} from "@/utils/auth";
	// 在 Vue 组件中使用 download 方法  
	import {
		download
	} from "@/utils/request";
	export default {
		components: {
		    notice,  
		  },  
		data() {
			return {
				confirmDialogVisible: false, // 控制弹窗显示
				businessType: 'experimental',
				showSearch: false,
				formData: {
					taskId: '',
					initiationTime: '',
					detectionNature: '',
					urgency: '',
					detectionMethod: '',
					monitoringPoints: '',
					pageNum: 1,
					pageSize: 10,
					queryType: ''
				},
				urgencyList: ['普通', '加急', '特急'],
				detectionMethods: ['现场采样', '送样'],
				tableData: [], // 数据列表  
				total: 0, // 总记录数  
				perms: '', // 提供一个默认字符串 
			};
		},
		mounted() {
			this.getList();
		},
		onLoad() {
			this.queryPerms();
		},
		methods: {
			queryPerms() {
			  	queryPerms().then(response => {  
			  	    console.log("queryAuthorize + response:==" + response);  
			  	    // 确保 response 是数组，或者解析为数组  
			  	    this.perms = Array.isArray(response) ? response : JSON.parse(response);  
			  	    console.log("queryAuthorize + this.perms:==" + this.perms);  
			  	  });  
			  },
			checkPerms(perm) {  
				// 如果是管理员（admin），则跳过权限检查
				if (this.perms.includes("admin")) {
				  return true;
				}
			  if (!this.perms || !Array.isArray(this.perms)) {  
			    return false;  
			  }  
			  return this.perms.includes(perm);  
			},
			openDialog() {
				this.confirmDialogVisible = true; // 打开弹窗  
			},
			// 搜索功能
			toggleSearch() {
				this.showSearch = !this.showSearch;
			},
			submitForm() {
				this.getList();
			},
			resetForm() {
				this.formData = {
					jobNumber: '',
					detectionNature: '',
					urgencyDegree: '',
					detectionMethod: '',
					monitoringPoints: '',
					initiationTime: '',
					queryType: '',
					pageNum: 1,
					pageSize: 10,
				};
			},
			getList() {
				this.formData.queryType = "3";
				list(this.formData).then(response => {
					this.tableData = response.rows;
					this.total = response.total;
					console.log(response)
				}).catch(() => {
					this.$message.error('获取数据失败');
				});
			},
			showFileDialog(item, type) {
				console.log('查看文件', item, type);
			},
			uploadFiles(item) {
				console.log('上传文件', item);
			},
			confirmSubmit(item) {
				console.log('提交任务', item);
			},

			toggleSuspend(index, row) {
				console.log(row);
				  if (row.killStatus == '1') {  
				    uni.showToast({  
				      title: '订单已终止不允许操作',  
				      icon: 'none',  
				      duration: 2000,  
				    });  
				    return false;  
				  } else {  
				    if (row.isSuspended) {  
				      row.isStop = '待挂起';  
				      this.$set(this.tableData[index], "isSuspended", false);  
				    } else {  
				      row.isStop = '待恢复';  
				      this.$set(this.tableData[index], "isSuspended", true);  
				    }  
				    update(row).then((response) => {  
				      if (response.msg === "操作成功") {  
				        uni.showToast({  
				          title: '操作成功',  
				          icon: 'success',  
				          duration: 2000,  
				        });  
				      }  
				    });  
				  }  

			},
			gotoReturnPage(item) {
				const tuihuiFrom = "experimentalAnalysis"; 
				uni.navigateTo({
					url: `/pages/business/common/return/index?taskId=${item.taskId}&tuihuiFrom=${tuihuiFrom}`,  
				});   
			},
			paifaSubmit(item) {
				console.log('派发任务', item);
			},
			changePage(e) {  
				this.formData.pageNum = e.current;  
				this.getList();  
			},
		},
	};
</script>


<style>
	/* 容器样式 */
	.container {
		padding: 12px;
		background-color: #f8f9fa;
	}

	/* 搜索表单 */
	.search-collapse-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		border: 1px solid #ddd;
		border-radius: 6px;
		padding: 10px 12px;
		margin-bottom: 10px;
	}

	.search-form {
		border-radius: 6px;
		background-color: #fff;
		padding: 14px;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 14px;
	}

	.label {
		width: 100px;
		font-size: 14px;
		color: #555;
		text-align: right;
		margin-right: 10px;
	}

	.input,
	.picker {
		flex: 1;
		padding: 6px 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}

	/* 列表样式 */
	.list {
		margin-top: 14px;
	}

	.list-item {
		padding-bottom: 12px;
	}

	/* 卡片样式 */
	.card {
		background-color: #fff;
		border-radius: 6px;
		padding: 14px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
		margin-bottom: 12px;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		font-weight: 600;
		color: #333;
	}

	.task-status {
		font-size: 14px;
	}

	.task-status.status-complete {
		color: green;
	}

	.file-status {
		margin-top: 10px;
	}

	.file-item {
		margin-bottom: 8px;
	}

	/* 按钮样式 */
	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 12px;
	}

	.action-btn {
		border-radius: 20px;
		padding: 6px 12px;
		font-size: 14px;
		font-weight: bold;
		color: #fff;
	}

	.action-btn.primary {
		background-color: #409eff;
	}

	.action-btn.success {
		background-color: #67c23a;
	}

	.action-btn.danger {
		background-color: #f56c6c;
	}

	.action-btn.info {
		background-color: #909399;
	}

	/* 分页组件 */
	.pagination {
		margin-top: 20px;
		text-align: center;
	}
</style>
